package com.zhkj.txg.module.member.ui

import android.graphics.Color
import android.view.View
import android.view.ViewTreeObserver
import androidx.core.widget.NestedScrollView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.zhkj.lib.base.ViewModelFragment
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.member.adapter.InterestHorizontalAdapter
import com.zhkj.txg.module.member.adapter.MemberProductAdapter
import com.zhkj.txg.module.member.entity.InterestEntity
import com.zhkj.txg.module.member.vm.MemberCardViewModel
import com.zhkj.txg.utils.GridItemDecoration
import kotlinx.android.synthetic.main.fragment_member_product.*

class MemberProductFragment : ViewModelFragment<MemberCardViewModel>() {

    private var maxScrollHeight: Int = 0

    // 会员权益Adapter
    private val horizontalAdapter = InterestHorizontalAdapter()

    // 会员礼包商品Adapter
    private val productAdapter = MemberProductAdapter().apply {
//        loadMoreModule?.isEnableLoadMore = true
//        loadMoreModule?.setOnLoadMoreListener {
//            viewModel.getProductList(AccountManager.getToken())
//        }
    }

    override val layoutResId: Int = R.layout.fragment_member_product
    override fun setViewModel(): MemberCardViewModel = createViewModel(true)
    override fun initViewModel() {
        viewModel.memberProductListLiveData.observe(this, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.let {
                    // 数据填充
                    if (it.loadMore) productAdapter.addData(it.data)
                    else productAdapter.setNewData(it.data)
                    // 判断加载状态
//                    if (it.hasMore) productAdapter.loadMoreModule?.loadMoreComplete()
//                    else productAdapter.loadMoreModule?.loadMoreEnd()
                    // 判断加载状态
                    if (it.hasMore) refreshLayout.finishLoadMore(0, true, false)
                    else refreshLayout.finishLoadMoreWithNoMoreData()
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
//                    productAdapter.loadMoreModule?.loadMoreFail()
                    refreshLayout.finishRefresh()
                    refreshLayout.finishLoadMore()
                }
            }
        })
        // 会员权益是否展开数据观察
        viewModel.interestExpand.observe(this, Observer { expandStatus ->
            viewModel.memberCardLiveData.value?.response?.data?.cardInfo?.let { info ->
                if (expandStatus) horizontalAdapter.setNewData(info.interest)
                else mutableListOf<InterestEntity>().also { list ->
                    list.add(InterestEntity().apply {
                        itemType = 0
                        info.interest.forEach { content.addAll(it.content) }
                    })
                    list.add(InterestEntity().apply {
                        itemType = 1
                        expand = false
                    })
                }.let {
                    horizontalAdapter.setNewData(it)
                }
            }
        })
    }

    override fun initUI() {
        titleMember.setFragmentStatusBar()
        // 获取变色的最大滚动距离
        titleMember.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                maxScrollHeight = (ScreenUtil.getScreenWidth(requireContext()) - titleMember.measuredHeight)
                titleMember.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })
        // 配置产品数据
        with(rvMemberProduct) {
            layoutManager = GridLayoutManager(activity, 2)
            addItemDecoration(
                GridItemDecoration(ScreenUtil.dip(requireContext(), 20), ScreenUtil.dip(requireContext(), 12))
            )
            adapter = productAdapter
        }
        // 滚动监听
        scrollView.setOnScrollChangeListener { _: NestedScrollView?, _: Int, scrollY: Int, _: Int, _: Int ->
            if (scrollY <= maxScrollHeight) {
                val alpha = (scrollY.toFloat() / maxScrollHeight * 255).toInt()
                titleMember.setBackgroundColor(Color.argb(alpha, 239, 214, 184))
            } else titleMember.setBackgroundColor(Color.argb(255, 239, 214, 184))
            ivMemberTop.visibility = if (scrollY > 2000) View.VISIBLE else View.GONE
        }
        // 滚动到顶部
        ivMemberTop.setOnClickListener {
            scrollView.smoothScrollTo(0, 0)
        }
        // 设置会员权益
        with(rvMemberInterest) {
            layoutManager = LinearLayoutManager(context)
            adapter = horizontalAdapter
        }
        horizontalAdapter.setOnItemChildClickListener { _, view, _ ->
            if (view.id == R.id.tvInterestFooter) viewModel.interestExpand.value =
                viewModel.interestExpand.value?.not() ?: false
        }
        with(refreshLayout) {
            setEnableRefresh(true)
            setEnableLoadMore(true)
            setOnRefreshListener {
                viewModel.getProductList(AccountManager.getToken(), true)
            }
            setOnLoadMoreListener {
                viewModel.getProductList(AccountManager.getToken(), false)
            }
        }
    }

    override fun initData() {
        viewModel.getProductList(AccountManager.getToken(), true)
        viewModel.interestExpand.value = false
    }
}